package com.another.bidservice.service.impl;

import com.another.bidservice.dao.mapper.CompanyDao;
import com.another.bidservice.entity.TCodeRule;
import com.another.bidservice.entity.TCompany;
import com.another.bidservice.entity.TUser;
import com.another.bidservice.dao.jpa.UserJPADao;
import com.another.bidservice.dao.mapper.UserDao;
import com.another.bidservice.service.IUserService;
import com.another.bidservice.utils.generator.GeneratorCodeForMysql;
import com.another.bidservice.utils.redis.RedisRepository;
import com.another.bidservice.utils.security.MD5Util;
import com.another.common.enums.CodeRuleEnum;
import com.another.common.enums.Enums;
import com.another.common.utils.common.DateUtil;
import com.another.common.utils.common.EmptyUtil;
import com.another.common.utils.common.MyException;
import com.another.common.utils.result.Result;
import com.another.common.utils.result.ResultEnum;
import com.another.common.utils.token.TokenUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
@Transactional
public class UserServiceImpl extends BaseServiceImpl implements IUserService {

    private Logger logger = Logger.getLogger(this.getClass());

    @Autowired
    private UserDao userDao;

    @Autowired
    private UserJPADao userJPADao;

    @Autowired
    private GeneratorCodeForMysql generatorCodeForMysql;

    @Autowired
    private RedisRepository redisRepository;

    @Autowired
    private CompanyDao companyDao;

    @Override
    public Result getList(TUser tUser) {
        String sql = "select * from db_sys.vt_user";
        List<TUser> list = userDao.getList(sql);
        if (EmptyUtil.isEmpty(list)) {
            return Result.success("没有查询到数据！", "");
        } else {
            return Result.success(list);
        }
    }


    @Override
    public Result insertList(List<TUser> tUsers) {
        int ret = userDao.insertList(tUsers);
        if (ret == tUsers.size()) {
            return Result.success("添加成功！", "");
        } else {
            throw new MyException(101, "添加失败！");
        }
    }


    @Override
    public Result deleteList(List<Integer> rowid) {
        int ret = userDao.deleteList(rowid);
        if (ret == rowid.size()) {
            return Result.success("删除成功！", "");
        } else {
            throw new MyException(101, "删除失败！");
        }
    }

    @Override
    public Result updateList(List<TUser> tUsers) {
        try {
            int ret = userDao.updateList(tUsers);
            return Result.success("修改成功！", "");
        } catch (Exception e) {
            logger.info(e.getMessage(), e);
            throw new MyException(101, "修改失败！");
        }
    }


    @Override
    public Result insertUser(TUser tUser) {
        try {

            if (EmptyUtil.isEmpty(tUser.getPhone())) {
                return Result.error("注意: 手机号信息没输入！");
            }

            tUser.setUserStatus(Enums.UserStatus.effective.getCode());

            List<TUser> list = userJPADao.findAllByPhoneAndUserStatus(tUser.getPhone(), tUser.getUserStatus());

            if (EmptyUtil.isNotEmpty(list)) {
                return Result.error("注意: 手机号已经存在了！");
            }

            if (EmptyUtil.isEmpty(tUser.getName())) {
                tUser.setName(tUser.getPhone());
            }

            //生成用户编号
            TCodeRule codeRule = new TCodeRule();
            codeRule.setSeqTypeId(CodeRuleEnum.USER_ID.getCode());
            codeRule.setSize(1);
            String userId = generatorCodeForMysql.GeneratorCode(codeRule);
            tUser.setUserId(userId);

            //设置密码
            String pwd = "";
            try {
                if (Enums.SYSTEM.DEFAULT_PWD.getCode().equals(tUser.getPassword())||EmptyUtil.isEmpty(tUser.getPassword())) {
                    pwd = Enums.SYSTEM.DEFAULT_PWD.getCode();
                } else {
                    pwd = MD5Util.md5(tUser.getPassword(), tUser.getUserId());
                }

            } catch (Exception e) {
                logger.info("生成密码错误", e);
                e.printStackTrace();
                throw new MyException(ResultEnum.ERROR.getCode(), "生成密码错误");
            }
            tUser.setPassword(pwd);


            tUser.setCreateId(tUser.getRequestUserId());
            tUser.setCreateDate(DateUtil.getNowDateByyyyyMMddHHmmss());

            TUser u = userJPADao.save(tUser);
            return Result.success("添加成功！", u);
        } catch (Exception e) {
            logger.info(e.getMessage(), e);
            throw new MyException(101, "添加失败！");
        }
    }

    @Override
    public Result updateUser(TUser tUser) {
        try {

            if (EmptyUtil.isEmpty(tUser.getUserId())) {
                return Result.error("注意: 用户id必传！");
            }

            tUser.setUpdateId(tUser.getRequestUserId());


            if (EmptyUtil.isNotEmpty(tUser.getPassword()) && !tUser.getPassword().equals(Enums.SYSTEM.DEFAULT_PWD.getCode())) {
                try {
                    String pwd = MD5Util.md5(tUser.getPassword(), tUser.getUserId());
                    tUser.setPassword(pwd);
                } catch (Exception e) {
                    logger.info("密码加密失败!", e);
                    e.printStackTrace();
                    throw new MyException("密码加密失败!");
                }
            }

            //查看手机号是否存在
            if (EmptyUtil.isEmpty(tUser.getPhone())) {
                List<TUser> list = userJPADao.findAllByUserIdIsNotAndPhoneIsAndUserStatusIs(tUser.getUserId(), tUser.getPhone(), Enums.UserStatus.effective.getCode());
                if (EmptyUtil.isNotEmpty(list)) {
                    return Result.error("注意: 此手机号以已经用户使用！");
                }

            }


            int ret = userDao.updateUser(tUser);
            return Result.success("修改成功！");
        } catch (Exception e) {
            logger.info(e.getMessage(), e);
            throw new MyException(101, "修改失败！");
        }
    }

    @Override
    public Result deleteUser(TUser tUser) {
        try {
            int ret = userDao.deleteUser(tUser);
            return Result.success("删除成功！", "");
        } catch (Exception e) {
            logger.info(e.getMessage(), e);
            throw new MyException(101, "删除失败！");
        }
    }


    /**
     * @param user
     * @return com.another.exhibitioncommon.utils.result.Result
     * @author Another
     * @description :  web端登陆
     * @date 2019/7/11
     * @version : 1.0
     */
    @Override
    public Result webLogin(TUser user, HttpServletRequest request) {


        //根据登录名查看是否存在用户
        List<TUser> users = userJPADao.findAllByPhoneAndUserStatus(user.getPhone(),Enums.UserStatus.effective.getCode());

        if (EmptyUtil.isEmpty(users)) {
            return Result.error("账户不存在！");
        }

        if (users.size() > 1) {
            throw new MyException(ResultEnum.ERROR.getCode(), "根据登录名查询到多个账户！" + user.getPhone());
        }

        TUser userInfo = users.get(0);

        // 密码校验是否正确
        if (Objects.equals(Enums.SYSTEM.DEFAULT_PWD.getCode(), user.getPassword()) &&
                Objects.equals(Enums.SYSTEM.DEFAULT_PWD.getCode(), userInfo.getPassword())) {
            // 初始密码校验
        } else {
            // 非初始密码校验
            String pwd;
            try {
                pwd = MD5Util.md5(user.getPassword(), userInfo.getUserId());
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
                e.printStackTrace();
                throw new MyException(ResultEnum.ERROR.getCode(), "系统错误，密码解析错误!请联系系统管理员");
            }
            if (!Objects.equals(userInfo.getPassword(), pwd)) {
                throw new MyException(ResultEnum.ERROR.getCode(), "密码错误!");
            }
        }

        // 获取用户信息


        setToken(userInfo);

        //获取用户所有公司
        TCompany model = new TCompany();
        model.setUserId(userInfo.getUserId());
        model.setCompanyStatus(Enums.CompanyStatus.ON.getCode());
        List<TCompany> companyModels = companyDao.getCompanysByUserId(model);


        if (EmptyUtil.isNotEmpty(model)) {
            userInfo.setCompanys(companyModels);
        }

        return Result.success("登陆成功!", userInfo);
    }


    public TUser setToken(TUser userLoginModel) {
        //设置Token过期时间
        Calendar c = Calendar.getInstance();
        c.add(Calendar.DAY_OF_MONTH, 1);
        Date date = c.getTime();

        String token = TokenUtil.createToken(userLoginModel.getUserId(), date);
        userLoginModel.setToken(token);
//        redisRepository.del(userLoginModel.getUserId()+"_"+userLoginModel.getSource());
        redisRepository.set(userLoginModel.getUserId() + "_" , userLoginModel, 12, TimeUnit.HOURS);

        return userLoginModel;
    }
}



